import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wechat/main.dart';
import 'package:flutter_wechat/page/discovery_page.dart';

class ChatListPage extends StatefulWidget {
  final List<ChatItemModel> list;

  final PopupMenuItemSelected<String> onSelected;

  const ChatListPage({this.list, this.onSelected, Key key}) : super(key: key);

  @override
  _ChatListPageState createState() => _ChatListPageState();
}

class _ChatListPageState extends State<ChatListPage> {
  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    return Scaffold(
        appBar: getMyAppBar(onSelected: widget.onSelected, title: "微信"),
        body: ListView.separated(
          padding: EdgeInsets.symmetric(vertical: 10.0),
          itemBuilder: (context, index) => ChatItemWidget(
                model: widget.list[index],
                index: index,
                onTap: (offset) {
                  _showMenu(context, offset);
                },
              ),
          itemCount: widget.list.length,
          separatorBuilder: (context, index) =>
              SeparatorWidget(mediaQuery.size.width),
        ));
  }

  _showMenu(BuildContext context,Offset tapPos) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject();
    final RelativeRect position = RelativeRect.fromLTRB(
        tapPos.dx, tapPos.dy,
        overlay.size.width - tapPos.dx,
        overlay.size.height - tapPos.dy
    );
    showMenu<String>(
        context: context,
        position: position,
        items: <PopupMenuItem<String>>[
          PopupMenuItem(
            child: Text("标为未读"),
          ),
          PopupMenuItem(
            child: Text("置顶聊天"),
          ),
          PopupMenuItem(
            child: Text("删除该聊天"),
          ),
        ]
    ).then<String>((String selected) {
      switch(selected){
        default:
          print('当前选中的是：$selected');
      }
    });
  }
}

class SeparatorWidget extends StatelessWidget {
  final double width;

  const SeparatorWidget(this.width);

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Container(
          height: 0.2,
          width: width - 55.0 - 15.0 - 6.0,
          color: Colors.grey,
        ),
      ],
    );
  }
}

class ChatItemWidget extends StatelessWidget {
  final ChatItemModel model;
  final ValueSetter<Offset> onTap;
  final int index;

  const ChatItemWidget({Key key, this.model, this.onTap, this.index})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var tapPos;
    List<Widget> _list = [];
    for (int i = 0; i < model.img.length; i++) {
      _list.add(Container(
        width: 12.0,
        height: 12.0,
        color: Colors.blue[100 * ((i + 1) % 15)],
      ));
    }
    return InkWell(
      onTapDown: (TapDownDetails details) {
        tapPos = details.globalPosition;
      },
      onLongPress: () {
        print("onTap: ${model.name}");
        onTap(tapPos);
      },
      child: Container(
        height: 70.0,
        padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Stack(
              alignment: Alignment.topRight,
              children: <Widget>[
                model.img.length == 1
                    ? Container(
                        width: 50.0,
                        height: 50.0,
                        margin: EdgeInsets.all(3.0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          color: Colors.blue[100 * ((index + 1) % 15)],
                        ),
                      )
                    : Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 2.0),
                        width: 50.0,
                        height: 50.0,
                        margin: EdgeInsets.all(3.0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0),
                          color: Colors.grey[300],
                        ),
                        child: Wrap(
                          spacing: 2.0, // gap between adjacent chips
                          runSpacing: 2.0,
                          children: _list,
                        ),
                      ),
                Offstage(
                    child: CircleAvatar(
                        child: Text(model.unreadCount.toString(),
                            style: TextStyle(
                                fontSize: 13.0,
                                color: Colors.white,
                                fontWeight: FontWeight.bold)),
                        backgroundColor: Colors.red,
                        radius: 9.0),
                    offstage: model.unreadCount == 0),
              ],
            ),
            const SizedBox(width: 10.0),
            Expanded(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text("${model.name}", style: TextStyle(fontSize: 16.0)),
                const SizedBox(height: 5.0),
                Text("${model.message}",
                    style: TextStyle(fontSize: 13.0, color: Colors.grey)),
              ],
            )),
            Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Text("${model.time}",
                    style: TextStyle(fontSize: 12.0, color: Colors.grey)),
                Offstage(
                    child: Icon(Icons.notifications_off,
                        size: 16.0, color: Colors.grey),
                    offstage: !model.receiveFlag),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

List<ChatItemModel> mockData() {
  return <ChatItemModel>[
    ChatItemModel(
        img: [""], name: "江德福", message: "明天一起去看看校长吧", time: "上午07:20"),
    ChatItemModel(img: [""], name: "校长", message: "不剃头", time: "晚上07:25"),
    ChatItemModel(
        img: [""],
        name: "安杰",
        message: "来喝咖啡吧",
        time: "下午15:30",
        unreadCount: 2),
    ChatItemModel(
        img: [""],
        name: "老丁",
        message: "来，杀一盘",
        time: "下午16:45",
        receiveFlag: true),
    ChatItemModel(img: [""], name: "江德华", message: "来吃面条", time: "中午12:10"),
    ChatItemModel(
        img: ["1", "2", "3", "4", "5", "6"],
        name: "炮校一群",
        message: "校长: 明天早起集合啊",
        time: "晚上09:00"),
    ChatItemModel(
        img: [""],
        name: "江亚菲",
        message: "给你发的短信看到了？",
        time: "晚上10:05",
        unreadCount: 3),
    ChatItemModel(
        img: [""], name: "江卫国", message: "全地形车开起来真爽", time: "上午09:45"),
    ChatItemModel(img: [""], name: "江卫东", message: "最后一颗子弹留给我", time: "昨天"),
    ChatItemModel(img: [""], name: "江卫民", message: "来喝大红袍，我请客", time: "昨天"),
    ChatItemModel(img: [""], name: "王海洋", message: "我还有课，下次吧", time: "昨天"),
    ChatItemModel(img: [""], name: "江亚宁", message: "我的小说出版了，叫父母爱情", time: "昨天"),
  ];
}

class ChatItemModel {
  final List<String> img;
  final String name;
  final String message;
  final String time;
  final bool isGroup;
  final bool isTop;
  final int unreadCount;
  final bool receiveFlag;

  const ChatItemModel(
      {this.img,
      this.name,
      this.message,
      this.time,
      this.isGroup = false,
      this.isTop = false,
      this.unreadCount = 0,
      this.receiveFlag = false});

  static ChatItemModel copy(ChatItemModel m) {
    return ChatItemModel(
        img: m.img,
        name: m.name,
        message: m.message,
        time: m.time,
        isGroup: m.isGroup,
        isTop: m.isTop);
  }
}
